package com.ruoyi.syf.handler.escalation;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.text.ParseException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 上报上下文环境对象
 */
@Service
public class StrategyFactory {

    private static final Logger logger = LoggerFactory.getLogger(StrategyFactory.class);

    //线程安全
    private final Map<String,EscalationStrategy> map = new ConcurrentHashMap<>();

    @Autowired
    private ApplicationContext applicationContext;

    /**
     * 初始化map容器
     */
    @PostConstruct
    private void init(){
        Map<String, EscalationStrategy> beansOfType = applicationContext.getBeansOfType(EscalationStrategy.class);
        beansOfType.forEach((k,v) -> {
            map.put(v.getEscalationType(),v);
        });
    }

    /**
     * 上报方法
     */
    public boolean escalation(String escalationType) {
        try {
            return map.get(escalationType).escalation();
        }catch (ParseException e){
            logger.error("上报失败，上报类型：【{}】,失败原因：=>{}",escalationType,e.getMessage());
            e.printStackTrace();
        }
        return false;
    }

}
